'''
Author: 红色梧桐 940120450@qq.com
Date: 2024-05-10 19:24:16
LastEditors: 红色梧桐 940120450@qq.com
LastEditTime: 2024-09-05 20:34:45
FilePath: \myReader\applications\configs\func.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from datetime import datetime, timedelta
import re
from passlib.context import CryptContext
from fastapi.templating import Jinja2Templates
import requests


# 渲染模板
def render_template(request, html, data=None):
    """
        渲染模板函数
    :param request: 请求对象
    :param html:    页面
    :param data:    参数
    :return:
    """
    if data is None:
        data = {}
    templates = Jinja2Templates(directory="templates")
    data["request"] = request
    return templates.TemplateResponse(html, data)


# 中文转数字
def chinese_to_num(chinese_num):
    # 检测chinese_num是否有中文
    if not re.compile(r'[\u4e00-\u9fff]').search(chinese_num):
        return chinese_num

    chinese_dict = {'零': 0, '一': 1, '二': 2, '三': 3, '四': 4, '五': 5, '六': 6, '七': 7, '八': 8, '九': 9, '十': 10, '百': 100, '千': 1000, '万': 10000}
    num = 0
    tmp = 0
    for i in range(len(chinese_num)):
        if chinese_num[i] in chinese_dict.keys():
            if chinese_num[i] == '十' or chinese_num[i] == '百' or chinese_num[i] == '千' or chinese_num[i] == '万':
                if chinese_num[i] == '十' and tmp == 0:
                    tmp = 1
                num += chinese_dict[chinese_num[i]] * tmp
                tmp = 0
            else:
                tmp += chinese_dict[chinese_num[i]]
    num += tmp
    return num


pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")


# 密码加密
def get_password_hash(password: str) -> str:
    return pwd_context.hash(password)


# 密码验证
def verify_password(plain_password: str, hashed_password: str) -> bool:
    return pwd_context.verify(plain_password, hashed_password)


# aigc 辅助函数
def aigc_func(type, data, params):
    url = "http://127.0.0.1:7564/get_ai_data"
    result = requests.post(url, json={'type': type, 'contents': data, 'params': params})
    return result.json()


# 解析时间格式
def parse_time_strings(time_str):
    current_date = datetime.now()
    try:
        if '年' in time_str:
            time_format = '%Y年 %m月 %d日 %H:%M'
            parsed_time = datetime.strptime(time_str, time_format)
        elif '昨天' in time_str:
            yesterday = current_date - timedelta(days=1)
            hour, minute = map(int, time_str[3:].split(':'))
            parsed_time = datetime(yesterday.year, yesterday.month, yesterday.day, hour, minute)
        elif '星期' in time_str:
            weekday_names = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
            weekday = weekday_names.index(time_str[:3])
            days_offset = (weekday - current_date.weekday()) % 7
            if days_offset == 0:
                days_offset = 7
            target_date = current_date - timedelta(days=current_date.weekday(), weeks=(days_offset // 7))
            hour, minute = map(int, time_str[3:].split(':'))
            parsed_time = datetime(target_date.year, target_date.month, target_date.day, hour, minute)
        else:
            p_str = time_str
            day = current_date.day
            month = current_date.month
            if '月' in time_str:
                day_str, p_str = time_str.split(' ')
                day_str_list = day_str.split('月')
                month = int(day_str_list[0])
                day = int(day_str_list[1].strip("日"))
            hour, minute = map(int, p_str.split(':'))  
            parsed_time = datetime(current_date.year, month, day, hour, minute)

        return parsed_time.strftime('%Y-%m-%d %H:%M:%S')
    except Exception:
        return time_str